/**
 * Created by litao on 2018/10/23.
 */
import 'element-ui/lib/theme-chalk/index.css'
import Element from 'element-ui';
import EasyScroll from 'easyscroll';
import routerTable from './router/routerTable';
import routerBefore from './router/routerBefore';
import validToken from './http/valid';
import restApi from './http/restApi';
import httpMocks from './http/mock/intercept';
import scanWraps from './warp';
import Encrypt from './encrypt';
import methods from './methods';

//http://jboot.e7lu.cn/1794101
import JBootComponent from 'jboot-component';

const keyMapping = {}, requestIsEncrypt = process.env.NODE_ENV === 'production';

export default function (context) {
    //安装elementUI
    context.install(Element, {size: 'mini'});

    context.$configure.set('methods', methods);

    //安装jboot组件库
    context.install(JBootComponent, {
        upload: {
            url: '/sys/attachment/upload' //全局上传地址
        }
    });

    setTimeout(() => {
        [
            {field: '$success', type: 'success'},
            {field: '$warn', type: 'warning'},
            {field: '$info', type: 'success'},
            {field: '$error', type: 'error'}
        ].forEach(({field, type}) => context.$vue.prototype[field] = message => setTimeout(() => Element.Message({
            message,
            type
        })));
    });

    //安装滚动条插件
    context.install(EasyScroll);

    //获取百度token
    context.$configure.set('getBdAudioApiToken', function () {
        return context.$vue.prototype.$nativeAjax.get(`/bdApiAuth/oauth/2.0/token?grant_type=client_credentials&client_id=pw152BzvaSZVwrUf3Z2OHXM6&client_secret=fa273cc704b080e85ad61719abbf7794`).then(response => {
            let accessToken = (response.data || {}).access_token;

            if (accessToken) {
                return accessToken;
            } else {
                throw '调用百度api时，出现异常，请检查代理设置';
            }
        });
    });

    //语音合成选填参数
    context.$configure.set('audioRequestParams', {
        per: 106,
        vol: 15
    });

    //请求加密
    context.$configure.set('requestIsEncrypt', false);

    //内置log打印
    context.$configure.set('inlayLog', true);

    //初始化全局封装
    context.$configure.set('globalWrap', scanWraps(context.utils.extractName));

    //是否启用mock
    context.$configure.set('mockFlag', process.env.NODE_ENV !== 'production');

    //设置http请求需要用到的httpToken的key值
    context.$configure.set('tokenKey', 'yf-token');

    //配置入口文件
    context.$configure.set('rootFileConfigure', function () {
        return {
            instance: function () {
                return require('../Root.vue').default;
            }
        }
    });

    context.$configure.set('routerAfter', () => setTimeout(() => {
        document.querySelector('.content-wrap').scrollTo(0, 0);
    }, 0));

    context.$configure.set('requestBeforeSend',function (config) {
        let data = config.data, random;

        if(requestIsEncrypt){
            // 生产随机密码
            random = Encrypt.getRandom(8);

            let encryptKey = Encrypt.rsaEncrypt(
                'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj8ad6cEYuE390m05wEC/\n' +
                'EB3qIWiq/iY6njWGWRN7E7VmTrs9JotAs+pUUZ14FTP6+3bLrfVcYYWsn877utak\n' +
                '6EzqnOFidkXRj9UdZ8KYFxBwaaftxdWOThD0BKbaSPYhNkDDd625wjdJ3+ACqHmX\n' +
                'qosKxlyr5kPRIarYbHcnTN2hy2+GVThDAE1rEXAZdFOvbCjWNGKYhLM94tlVezlk\n' +
                'sVoC6YRocx3IC4QEf9gzb0SkUTch5Xa6gzd6kypYSZjK5MBbXvDe523k5AAK9ytr\n' +
                'plshDhseW0RU3h11iVBaQ4Hho7E32Z2Huy23w0RwFh52NZzwjhVh9JJRr8zD6i4X\n' +
                'PwIDAQAB',
                random);

            // 密码RSA加密
            config.headers['a-k-l-t'] = encryptKey;

            keyMapping[encryptKey] = random;
        }

        if(data){
            // if(data.pageNum && data.pageSize && !config.url.includes('pageNum')){
            //     let pageParamStr = ['pageNum', 'pageSize'].map(name => `${name}=${data[name]}`).join('&');
            //
            //     config.url = config.url.includes('?') ? config.url + pageParamStr : config.url + '?' + pageParamStr;
            // }

            if(requestIsEncrypt){
                // 数据加密
                config.data = Encrypt.tripleDESEncrypt(random, JSON.stringify(data));
            }
        }
    });

    //路由模式
    context.$configure.set('routerMode', 'history');

    //自动注册组件上下文
    context.$configure.set('componentContext', require.context('@/components/', true, /\.vue$/));

    //路由表配置
    context.$configure.set('routerTable', routerTable);

    //跳转之前的拦截
    context.$configure.set('routerBefore', routerBefore.bind(null, context));

    //验证token是否过期
    // context.$configure.set('validToken', validToken);

    //http请求基础路径
    // context.$configure.set('httpBaseUrl', process.env.NODE_ENV === 'production' ? '/__api/' : 'http://192.168.10.162:8080');
    context.$configure.set('httpBaseUrl', process.env.NODE_ENV === 'production' ? '/__api/' : 'http://127.0.0.1:6891');
    // context.$configure.set('httpBaseUrl', process.env.NODE_ENV === 'production' ? '/__api/' : 'http://tb.wanghuifeng.me/__api/');
    // context.$configure.set('httpBaseUrl', process.env.NODE_ENV === 'production' ? 'http://parking.wanghuifeng.me/__api' : 'http://parking.wanghuifeng.me/__api');
    // context.$configure.set('httpBaseUrl', process.env.NODE_ENV === 'production' ? 'http://parking.wanghuifeng.me/__api' : 'http://parking.wanghuifeng.me/__api');
    // http://47.105.197.148:6831
    //restApi
    context.$configure.set('restApi', restApi.bind(null, context));

    //httpMocks
    context.$configure.set('httpMocks', httpMocks);


    context.$configure.set('httpSuccessHandler', function (response, cb) {
        let isJsonResponse = response.config.responseType === 'json',
            isStreamResponse = response.headers['content-type'] === 'application/octet-stream',
            responseIsSuccess = response.data.code === 200 || (isJsonResponse && response.data) || isStreamResponse;

        if(requestIsEncrypt && responseIsSuccess && !isStreamResponse){
            let encryptKey = response.config.headers['a-k-l-t'],
                key = keyMapping[encryptKey];

            delete keyMapping[encryptKey];

            if(key){
                let responseData;

                if(response.data.data){
                    let decryptResponse = Encrypt.tripleDESDecrypt(key, response.data.data);

                    try {
                        decryptResponse = JSON.parse(decryptResponse);
                    } catch (e) {}

                    responseData = Object.assign({}, response.data, {
                        data: decryptResponse
                    })
                }else{
                    responseData = Encrypt.tripleDESDecrypt(key, response.data);
                }

                response.data = responseData;
            }
        }

        cb(responseIsSuccess);
    });

    //请求异常拦截
    // context.$configure.set('httpErrorHandler', function (error, cb) {
    //     cb();
    // });
    // //请求异常拦截
    context.$configure.set('httpErrorHandler', function (error, cb) {
        if (error.response && [401, 901].includes((error.response.data || {}).code)) {
            context.$rootInstance.$jump("/login");
            context.$rootInstance.$nextTick(function () {
                context.$rootInstance.$busBroadcast('user-auth-fail', error);
            });
        } else {
            cb();
        }
    });
}
